package com.example.wechat114.config;

import com.example.wechat114.commons.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;

/**
 * @Atuthor:Likao
 * @Description:
 * @Date:Created in 15:00 2022-04-15
 * @Modified By:
 */
@Configuration
public class CacheConfig  extends CachingConfigurerSupport {

    @Autowired
    private RedisCache redisCache;

    @Bean("SimpleCacheManager")
    public SimpleCacheManager cacheManager() {

        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();

        redisCache.setName("hospitalCache");

        HashSet<Cache> set = new HashSet<>();
        set.add(redisCache);
        simpleCacheManager.setCaches(set);

        return  simpleCacheManager;
    }
    //键值生成策略
    @Override
    public KeyGenerator keyGenerator() {
        return super.keyGenerator();
    }

    @Bean("hospital")
    public KeyGenerator hospitalKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(RedisCacheKey.HOSPITAL_PRE);
            sb.append(":");
            if (params.length==0){
                sb.append(method.getName());
            }else {
                sb.append(params[0]);
            }
          return sb.toString();
        };
    }
    @Bean("department")
    public KeyGenerator departKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(RedisCacheKey.DEPART_PRE);
            sb.append(":");
            if (params.length==0){
                sb.append(method.getName());
            }else {
                sb.append(params[0]);
            }
            return sb.toString();
        };
    }


}
